package com.goodfox.web.generic.role.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.attribute.entity.Attribute;
import com.goodfox.web.generic.authority.filter.SecurityMetadataSourceImpl;
import com.goodfox.web.generic.authority.service.PowerService;
import com.goodfox.web.generic.authority.service.ResourcesService;
import com.goodfox.web.generic.function.entity.Function;
import com.goodfox.web.generic.function.service.FunctionService;
import com.goodfox.web.generic.organization.service.OrganizationService;
import com.goodfox.web.generic.provide.entity.Pager;
import com.goodfox.web.generic.provide.exception.EntityValidateException;
import com.goodfox.web.generic.provide.service.EntityService;
import com.goodfox.web.generic.provide.service.GradeService;
import com.goodfox.web.generic.provide.util.ParameterUtil;
import com.goodfox.web.generic.provide.util.AttributeUtil;
import com.goodfox.web.generic.role.entity.Role;
import com.goodfox.web.generic.role.service.RoleService;

@Controller
@RequestMapping("/role")
public class RoleController{

	/** log4j日志器 */
	private Logger logger=Logger.getLogger(RoleController.class);

	/** 角色Service */
	@Autowired
	private RoleService roleService;
	
	/** 层级Service */
	@Autowired
	private GradeService gradeService;
	
	/** 组织机构Service */
	@Autowired
	private OrganizationService organizationService;
	
	/** 资源Service */
	@Autowired
	private ResourcesService resourcesService;
	
	/** 数据安全service */
	@Autowired
	private SecurityMetadataSourceImpl securityMetadataSource;

	/** 权限Service */
	@Autowired
	private PowerService powerService;
	
	/** 功能Service */
	@Autowired
	private FunctionService functionService;
	
	/** 实体Service */
	@Autowired
	private EntityService entityService;
	
	/**
	 * 进入角色管理首页
	 * @return 目标页面
	 */
	@RequestMapping(value="goRoleIndex.shtml")
	public String goRoleIndex(HttpServletRequest request,ModelMap model){
		logger.info("进入角色管理首页");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			List<Attribute> scopeList;
			if(loginAccount.getRole().getRoleScope().equals("0")){
				scopeList=AttributeUtil.queryAttrListByType("适用范围");
			}else{
				scopeList=new ArrayList<Attribute>();
				scopeList.add(AttributeUtil.getAttribute("适用范围", loginAccount.getRole().getRoleScope()));
			}
			model.put("scopeList", scopeList);

			int currentPage=1;
			if(!ParameterUtil.getReqParaValue(request,"pageNum").equals("")){
				currentPage=Integer.parseInt(ParameterUtil.getReqParaValue(request,"pageNum"));
			}
			int numPerPage=15;
			if(!ParameterUtil.getReqParaValue(request,"numPerPage").equals("")){
				numPerPage=Integer.parseInt(ParameterUtil.getReqParaValue(request,"numPerPage"));
			}
		    Map queryMap=entityService.fillQueryMap(request,model);
			Pager<Role> pager=roleService.queryRolePager(currentPage, numPerPage, queryMap);
		    model.put("roleList", pager.getEntityList());
			
			model.put("totalCount", pager.getAllCount());
			model.put("currentPage", currentPage);
			model.put("numPerPage", numPerPage);
			
			return "role/roleIndex";
		}else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入角色添加页面
	 * @param request
	 * @param model
	 * @return 目标页面
	 */
	@RequestMapping(value="goRoleAdd.shtml")
	public String goRoleAdd(HttpServletRequest request,ModelMap model){
		logger.info("进入角色添加首页");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			List<Attribute> scopeList;
			if(loginAccount.getRole().getRoleScope().equals("0")){
				scopeList=AttributeUtil.queryAttrListByType("适用范围");
			}else{
				scopeList=new ArrayList<Attribute>();
				scopeList.add(AttributeUtil.getAttribute("适用范围", loginAccount.getRole().getRoleScope()));
			}
			model.put("scopeList", scopeList);
			
			//系统所有功能列表写入页面
			Set<Function> funSet=functionService.queryFunctionSetByScope(loginAccount.getRole().getRoleScope());
			model.put("funSet", funSet);
		
			return "role/roleAdd";
		}else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行角色添加操作，数据入库
	 * @param request
	 * @return 目标页面
	 */
	@RequestMapping(value="roleAdd.shtml")
	@ResponseBody
	public Map roleAdd(HttpServletRequest request){
		logger.info("执行角色添加");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "roleHome");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "closeCurrent");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				String roleName=ParameterUtil.getReqParaValue(request, "act_add_roleName");
				boolean isHave=roleService.isHave(roleName);
				if(isHave){
					message="新增失败！此角色名已存在";
				}else{
					Role entity=(Role)entityService.fillEntity(request,Role.class);
					roleService.addRole(entity,request.getSession().getAttribute("loginLogId").toString());
					securityMetadataSource.loadResourceDefine();
					statusCode="200";
					message="新增成功";
				}
			}catch(EntityValidateException evex){
				message="新增失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("roleAdd异常：",ex);
				message="新增失败:发生异常";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("roleAdd rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入角色修改页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goRoleModify.shtml")
	public String goRoleModify(HttpServletRequest request,ModelMap model){
		logger.info("进入角色更新首页");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			List<Attribute> scopeList;
			if(loginAccount.getRole().getRoleScope().equals("0")){
				scopeList=AttributeUtil.queryAttrListByType("适用范围");
			}else{
				scopeList=new ArrayList<Attribute>();
				scopeList.add(AttributeUtil.getAttribute("适用范围", loginAccount.getRole().getRoleScope()));
			}
			model.put("scopeList", scopeList);
			
			List<Function> funList=functionService.queryFunctionListByScope(loginAccount.getRole().getRoleScope(),"1");
			
			Role role=roleService.getRole(ParameterUtil.getReqParaValue(request, "roleId"));

			for(Function sysFun:funList){
				for(Function roleFun:role.getFunList()){
					if(sysFun.getFunId().equals(roleFun.getFunId())){
						sysFun.setIsChoise(1L);
						break;
					}
				}
			}
			//功能列表重新排序填充
			Set<Function> funSet=functionService.orderFillingFunSet(funList);
			model.put("funSet", funSet);
			
			//将目标角色对象回写到页面
			model.put("role", role);
	
			return "role/roleModify";
		}else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行角色修改操作，数据入库
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="roleModify.shtml")
	@ResponseBody
	public Map roleModify(HttpServletRequest request){
		logger.info("执行角色更新");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "roleHome");
		rspMap.put("callbackType", "update");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Role newEny=(Role)entityService.fillEntity(request,Role.class);
				Role oldEny=roleService.getRole(newEny.getRoleId());
				roleService.modifyRole(oldEny,newEny,request.getSession().getAttribute("loginLogId").toString());
				securityMetadataSource.loadResourceDefine();
				statusCode="200";
				message="更新成功！";
			}catch(EntityValidateException evex){
				message="更新失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("roleModify异常：",ex);
				message="更新失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("roleModify rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入角色查询页面
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="goRoleDetail.shtml")
	public String goRoleDetail(HttpServletRequest request,ModelMap model){
		logger.info("进入角色查看首页");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			Role role=roleService.getRole(ParameterUtil.getReqParaValue(request, "roleId"));
			model.put("role", role);
			Set<Function> funSet=functionService.orderFillingFunSet(role.getFunList());;
			model.put("funSet", funSet);
			return "role/roleDetail";
		}else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行角色删除操作，数据物理删除
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="roleRemove.shtml")
	@ResponseBody
	public Map roleRemove(HttpServletRequest request){
		logger.info("执行角色移除");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "reload");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				String roleId=ParameterUtil.getReqParaValue(request, "roleId");
				if(roleService.isBindingAccount(roleId)){
					message="该角色有绑定的人员，不能移除！";
				}else{
					Role entity=roleService.getRole(roleId);
					roleService.removeRole(entity,request.getSession().getAttribute("loginLogId").toString());
					statusCode="200";
					message="移除成功！";
				}
			}catch(Exception ex){
				logger.error("roleDelete异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("roleRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行角色批量移除
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="roleRemoveBat.shtml")
	@ResponseBody
	public Map roleRemoveBat(HttpServletRequest request){
		logger.info("执行角色批量移除");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "reload");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				message="";
				String[] roleIds=request.getParameterValues("roleIds");
				for(String roleId:roleIds){
					Role entity=roleService.getRole(roleId);
					if(roleService.isBindingAccount(roleId)){
						message+=entity.getRoleName()+"有绑定的人员，不能移除！";
					}else{
						roleService.removeRole(entity,request.getSession().getAttribute("loginLogId").toString());
						message+=entity.getRoleName()+"移除成功！";
					}
				}
				statusCode="200";
			}catch(Exception ex){
				logger.error("accountRemove异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("accountRemove rspMap:"+rspMap);
		return rspMap;
	}

	/**
	 * 判断角色名称是否存在
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("isHave.shtml")
	@ResponseBody
	public boolean isHave(HttpServletRequest request) {
		boolean have=false;
		try{
			if(roleService.isHave(ParameterUtil.getReqParaValue(request, "roleName"))){
				have=true;
			}
		}catch(Exception ex){
			logger.error("判断角色名异常", ex);
		}
		return have;
	}
}
